import base64
from openai import OpenAI

class qwenVL:
    def __init__(self, image_path, question):
        self.image_path = image_path
        self.question = question

    def main(self):
        # 对图片进行base64编码
        with open(self.image_path, "rb") as image_file:
            base64_image = base64.b64encode(image_file.read()).decode("utf-8")

        client = OpenAI(
            # 替换为你的通义千问api - key，如果没有先去官网注册一个
             api_key='',
             base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        )
        completion = client.chat.completions.create(
            # 采用的模型，也能替换为你想要的
            model="qwen-vl-max",
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text": self.question,
                        },
                        {
                            "type": "image_url",
                            "image_url": {
                                # 需要注意：传入base64编码前需要增加前缀 data:image/{图片格式};base64,{base64编码}
                                "url": f"data:image/png;base64,{base64_image}"
                            },
                        },
                    ],
                }
            ]
        )
        print(completion.choices[0].message.content)
        with open('output_qwen.txt', 'a') as file:
            # 遍历列表，将每个元素写入文件
            for result in completion.choices[0].message.content:
                file.write(result)
            file.write('\n')

